package com.zzj.handle;


import com.zzj.base.Result;
import com.zzj.base.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;


@Log4j2
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = NullPointerException.class)
    public Result<Object> exceptionHandler(NullPointerException e) {
        log.error("空指针异常", e);
        return Result.error("发生空指针异常");
    }

    /**
     * 请求参数验证异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<Object> exceptionHandler(MethodArgumentNotValidException e) {

        return Result.error(ResultCode.PARAM_ERROR.getCode(),
                ResultCode.PARAM_ERROR.getMsg() + ":" + e.getBindingResult().getAllErrors().stream()
                        .map(ObjectError::getDefaultMessage)
                        .collect(Collectors.joining("; ")));


    }

    @ExceptionHandler(value = Exception.class)
    public Result<Object> exceptionHandler(Exception e) {
        log.error("异常", e);
        return Result.error("发生异常:" + e.getMessage());
    }


}
